import { Component, OnInit, ViewChild, OnDestroy, AfterContentInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import {SettingsService, TitleService} from '@delon/theme';
import { Constant, ServiceResult } from '@core/constant';
import { ProductService } from '../../../../service/prod/product.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import {plService} from "../../../../service/pl/pl.service";

@Component({
  selector: 'replan-view-edit',
  templateUrl: './replan-edit.component.html',
  styleUrls: ['./replan-edit.component.less']
})
export class plViewEditComponent implements OnInit, OnDestroy {
  product:  any = {
    id:null,
    orderNo: null,
    bpmStatus:null,
    orderInfo: null,
    cusName: null,
    refPeriod: null,
    refTotalPeriod: null /*No show*/,
    refDate: null,
    refFbenjin: null,
    refAmount: null,
    refLixi: null,
    refSybenjin: null,
    reMark: null,
    payAmount: null,
    fxjOut58: null, /* 逾期天数 */
    fxjOut59:null /* 实际还款日期 */
  };
  // 预览图片地址
  bpmStatus =  [{text: '未还款', value: '未还款'}, {text: '已还款', value: '已还款'}];
  picUrl = '';
  // 图片上传地址
  uploadUrl = '';


  MAX_COUNT = 60;
  tabIndex = 0;
  saleing = false;
  private sub: any;

  constructor(
    public setting: SettingsService,

    private msg: NzMessageService,
    private modalService: NzModalService,
    private plService: plService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private cnt: Constant,
    private router: Router,
    private comm: CommService
  ) {}

  ngOnInit(): void {

    // this.loadbpmStatus();


    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      this.product.id = params["id"];
      // 获取商品详情
      this.getProductInfo();
    });
    // 隐藏reusetab
    setTimeout(() => {
        this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 100);
    this.titleService.setTitle("编辑产品")
  }

  // 显示reusetab
  ngOnDestroy() {
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }

  changeTab(index) {
    // 使用异步的方式更新组件, 防止ngIf错误
    Promise.resolve(null).then(() => this.tabIndex = index);
  }



  getProductInfo() {
    this.plService.getProduct(this.product.id).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      console.log("log"+JSON.stringify(data));
      this.product = data.data;

    })
  }

  loadbpmStatus() {
    this.bpmStatus = [];
    this.comm.getType("bpm_status").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.bpmStatus.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  beforeUpload = (file: File) => {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      if (!isJPG && !isPNG) {
          this.msg.warning(`不支持的格式: ${file.type}`);
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
          this.msg.warning('图片不能超过2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
  }

  private getBase64(img: File, callback: (img: any) => void) {
      if (img) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
      }
  }

  handleChange(row, col, info: { file: UploadFile }) {
      if (info.file.status === 'uploading') {
          return;
      }
      if (info.file.status === 'done') {
          let that = this;
          let f = info;
          this.getBase64(info.file.originFileObj, (img: any) => {
            that.picUrl = img;
            that.product.img =  f.file.response.rows[0].id;
          });
      }
      if (info.file.status === 'error') {
          this.msg.error(info.file.error.error);
      }
  }

  formatterYuan = value => `¥ ${value}`;
  parserYuan = value => value.replace('¥', '');

  formatterDollor = value => `${value}`;
  parserDollor = value => value.replace('$', '');

  back() {
    this.router.navigate(['/pl/replan']);
  }
  save() {
    let fxjPlReplan = {
      updateBy:this.setting.user.username,
      id:this.product.id,
      bpmStatus:this.product.bpmStatus,
      orderInfo: this.product.orderInfo,
      cusName: this.product.cusName,
      refPeriod: this.product.refPeriod,
      refTotalPeriod: this.product.refTotalPeriod /*No show*/,
      refDate: this.product.refDate,
      refFbenjin: this.product.refFbenjin,
      refAmount: this.product.refAmount,
      refLixi: this.product.refLixi,
      refSybenjin: this.product.refSybenjin,
      reMark: this.product.reMark,
      payAmount: this.product.payAmount,
      fxjOut58: this.product.fxjOut58,
      fxjOut59: this.product.fxjOut59,

    };
    // 调用接口
    this.plService.editPro(fxjPlReplan).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      if (data.ok === true) {
        this.msg.success('还款成功');
        this.back();
        this.emit.sendMessage("RELOAD_GOODS_LIST");
      } else {
        this.msg.error(data['message']);
      }
    })
  }

  changeColor(res) {
    this.product.colorSort = res.color.hex;
  }
}
